<?php

/**
 * Created by PhpStorm.
 * User: GadflyBSD
 * Date: 16/3/12
 * Time: 11:38
 */
class CommonAction extends Action{
	/**
	 * 客户端浏览器信息
	 * @var
	 */
	protected $browser;
	protected $weixin;
	protected $param;
	protected $cache;
	public $baseUrl;

	public function _initialize(){
		header("Content-type: text/html; charset=utf-8");
		Vendor('Browser');
		Vendor('Weixin');
		$this->param = D('Public')->getParam();
		$this->weixin = new Weixin($this->param['weixin']);
		$this->browser = new Browser();
		$this->cache = D('Public')->getCache();
		//B('LoginCheck');
		$assign = array('wxconfig' => $this->weixin->get_wxconfig(APP_URL.__SELF__));
		$this->assign(array_merge($assign, $this->getEnv()));

	}

	public function phpinfo(){
		phpinfo();
	}

	/**
	 * 微信浏览器第一次跳转控制器, 用于获取第三方网页授权页面链接
	 */
	public function WxIndex(){
		header("Location: ".$this->weixin->get_auth2_url(APP_URL.U(MODULE_NAME.'/run', array('an' => I('get.an'), 'px' => I('get.px')))));
	}

	/**
	 * 验证是否是微信浏览器,第二次跳转进入微信端入口
	 */
	public function run(){
		if($this->checkWeixin()){
			if(I('get.an')){
				$px = (I('get.px'))?'#/'.I('get.px').'/':'#/';
				header("Location: ".APP_URL.U(MODULE_NAME.'/wxPage').$px.I('get.an'));
			}else{
				$this->display('wxPage');
			}
		}else{
			$this->error('失败: 非法的页面请求!');
		}
	}

	/**
	 * 微信端入口控制器
	 */
	public function wxPage(){
		$this->display();
	}

	/**
	 * 微信第三方页面获取相关微信数据
	 * @return bool 返回第三方认证结果
	 */
	protected function checkWeixin(){
		$param = D('Public')->getParam();
		if($this->browser->isMobile() && $this->weixin->isWechat() && $_GET['code']){
			$token = $this->weixin->get_auth2_userinfo($_GET['code'], strtolower($param['weixin']));
			$sess = D('Public')->getSession(true, $token['openid'], $token);
			if($sess['errcode'] == 0)
				return true;
			else
				return false;
		}elseif($_GET['debug']==1){
			return true;
		}else{
			return false;
		}
		return true;
	}

	public function angular(){
		$request = $_SERVER['REQUEST_METHOD'];
		log::write($request);
		if(IS_POST || $request == 'POST'){
			$post = json_decode(file_get_contents('php://input'),true);
			log::write(json_encode_plus($post));
			$module = $post['ac'].'Ajax';
			if(method_exists($this, $module))
				$return = call_user_func(array(&$this, $module), $post);
			else
				$return = array('errcode' => 10001, 'msg' => '系统没有找到'.$module.'方法', 'data' => $post);
			if(is_array($return))
				$this->ajax($return);
			else
				echo $return;
		}else{
			return array('errcode' => 10001, 'msg' => '请求失败!');
		}
	}

	public function setSmsCache(){
		Vendor('CtcSms');
		$sms = new CtcSms();
		echo $sms->setCache();
	}

	public function verifyImg(){
		import('ORG.Util.Image');
		if(IS_AJAX && IS_POST){
			header('Content-Type: application/json; charset=utf8');
			if(session('verify') == md5($_POST['vdcode']))
				echo 'true';
			else
				echo 'false';
		}else{
			ob_end_clean();
			Image::buildImageVerify(5, 1);
		}
	}

	protected function sendSms($post, $param='WKSHOP'){
		Vendor('CtcSms');
		$sms = new CtcSms();
		$info = session(strtolower($param));
		return $sms->send($post['mobile'], $info['sideInfo']['uid'], $post['action']);
	}

	/**
	 * 生成并在页面输出显示二维码
	 * @param $url
	 */
	public function qrcode(){
		vendor("phpqrcode.phpqrcode");
		QRcode::png(urldecode(I('get.s')), false, 'L', 10, 1);
	}

	/**
	 * 上传文件
	 * @return array
	 */
	protected function uploadAjax(){
		if (empty($_FILES)) return array('type' => 'error', 'message' => 'No files found for upload.', 'file' => $_FILES);
		$success = null;
		$paths= array();
		$filePath = '/'.I('post.group', 'Verify').'/'.I('post.path', 'idcard').date('/Y/md/');
		$targetPath = str_replace('//', '/', C('UPLOAD_PATH'));
		if(!file_exists($targetPath.$filePath)) mkdirs($targetPath.$filePath, 0755, true);
		foreach($_FILES AS $k => $upload){
			$newName = $filePath.uploadName($upload['name']);
			if(move_uploaded_file($upload['tmp_name'], $targetPath.$newName)){
				$success = true;
				$paths[] = $newName;
				$src[] = imgSrc($newName, I('post.width', '300'), I('post.height', '225'));
			}else{
				$success = false;
				break;
			}
		}
		if($success === true){
			$output = array_merge(array('type' => 'success', 'content' => '上传文件成功！', 'target' => $paths, 'src' => $src), $this->getAjaxToken());
		}elseif($success === false){
			$output = array('type' => 'error', 'content' => 'Error while uploading images. Contact the system administrator');
			foreach ($paths as $file) {
				unlink($file);
			}
		} else {
			$output = array('type' => 'error', 'content' => 'No files were processed.');
		}
		return $output;
	}

	/**
	 * Ajax方式返回数据到客户端
	 * @access protected
	 * @param mixed $data 要返回的数据
	 * @param String $type AJAX返回数据格式
	 * @param Bool  $log    是否在服务器上记录LOG
	 * @param bool  $isMsg
	 *
	 * @return void
	 */
	public function ajax($param, $type='', $isMsg=true) {
		if(empty($type)) $type  =   C('DEFAULT_AJAX_RETURN');
		switch (strtoupper($type)){
			case 'JSON' :
				// 返回JSON数据格式到客户端 包含状态信息
				header('Content-Type:application/json; charset=utf-8');
				if($isMsg)
					exit(json_encode_plus($this->returnMsg($param)));
				else
					exit(json_encode_plus($param));
			case 'XML'  :
				// 返回xml格式数据
				header('Content-Type:text/xml; charset=utf-8');
				if($isMsg)
					exit(xml_encode($this->returnMsg($param)));
				else
					exit(xml_encode($param));
			case 'JSONP':
				// 返回JSON数据格式到客户端 包含状态信息
				header('Content-Type:application/json; charset=utf-8');
				$handler  =   isset($_GET[C('VAR_JSONP_HANDLER')]) ? $_GET[C('VAR_JSONP_HANDLER')] : C('DEFAULT_JSONP_HANDLER');
				if($isMsg)
					exit($handler.'('.json_encode_plus($this->returnMsg($param)).');');
				else
					exit($handler.'('.json_encode_plus($param).');');
			case 'EVAL' :
				// 返回可执行的js脚本
				header('Content-Type:text/html; charset=utf-8');
				if($isMsg)
					exit($this->returnMsg($param));
				else
					exit($param);
			case 'ARRAY':
				// 返回PHP数组或对象
				header('Content-Type:text/html; charset=utf-8');
				if($isMsg)
					exit(dump($this->returnMsg($param)));
				else
					exit(dump($param));
			default     :
				// 用于扩展其他返回格式数据
				if($isMsg)
					tag('ajax_return', $this->returnMsg($param));
				else
					tag('ajax_return', $param);
		}
	}

	protected function returnMsg($param){
		if(isset($param['errcode'])){
			$msg = ($this->cache['message'][$param['errcode']])?$this->cache['message'][$param['errcode']]:'未知的相关操作提示信息';
			$param['msg'] = ($param['msg'])?$param['msg']:$msg;
			$return = array(
				'type'      => ($param['errcode'] == '0')?'Success':'Error',
				'content'   => ($param['content'])?$param['content']:$param['msg'],
				'title'     => ($param['errcode'] == '0')?'操作成功啦!':'操作失败啦!',
				'icon'      => ($param['errcode'] == '0')?'fa-check':'fa-remove'
			);
			$return = array_merge($return, $param);
		}else{
			$return = array(
				'type'      => 'Error',
				'content'   => '未指定的错误或未指定错误编码',
				'msg'       => '未指定的错误或未指定错误编码',
				'title'     => '操作失败啦!',
				'icon'      => 'fa-remove',
			);
		}
		/*if(C('APP_DEBUG_LOG')){
			if($this->browser->getBrowser() == 'Chrome'){
				Vendor('ChromePhp');
				$log = $return;
				if(is_array($log['data'])){
					ChromePhp::table($log['data']);
					//log::write(json_encode_plus($log['data']), 'DATA');
					unset($log['data']);
				}
				ChromePhp::log($log);
				foreach(M()->db()->getTables() AS $val){
					$table = substr(strrchr($val, C('DB_PREFIX')), strlen(C('DB_PREFIX')));
					$sql[$val] = M($table)->getLastSQL();
					if($return['errcode']!='0'){
						$return['sql'][$val] = $sql[$val];
						//log::write(json_encode_plus($sql[$val]), $val);
					}
				}
				ChromePhp::group($sql);
				ChromePhp::groupEnd();
				/*if($return['errcode']!='0')
					log::write(json_encode_plus($log), $return['errcode']);
			}
		}*/
		return $return;
	}

	private function getEnv(){
		$wkshopInfo = session('wkshopInfo');
		$env = array(
			'meta'        => array(
				'author'        => 'GadflyBSD@gmail.com',
				'copyright'     => '2013-2016 Hyct Inc.',
				'appurl'        => APP_URL,
				'angular'       => (defined('GROUP_NAME'))?U(GROUP_NAME.'/'.MODULE_NAME.'/angular'):U(MODULE_NAME.'/angular'),
				'qrcodeUrl'     => ($wkshopInfo['md5key'])?U(MODULE_NAME.'/qrcode', array('s' => $wkshopInfo['md5key'])):U(MODULE_NAME.'/qrcode'),
				'shopTitle'     => ($wkshopInfo['title'])?$wkshopInfo['title']:null,
				'action'        => ACTION_NAME,
				'module'	    => MODULE_NAME,
			)
		);
		return $env;
	}
}